package com.kapo.egroup.security.domain;

import com.alibaba.fastjson.annotation.JSONField;
import com.kapo.egroup.entity.base.user.User;
import com.kapo.egroup.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * 登录用户身份权限
 *
 * @author starsea
 * @date 2022-07-13 14:47
 */

/**
 * LoginUser类
 * 实现UserDetails类
 * 需要实现7个方法
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
public class LoginUser implements UserDetails {

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 过期时间
     */
    private Long expireTime;


    /**
     * 用户信息
     */
    private User user;

    public LoginUser(User user) {
        this.user = user;
        this.userId = user.getId();
    }

    @JSONField(serialize = false)
    private Collection<? extends GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        if(StringUtils.isNotNull(user.getEmail()))return user.getEmail();
        else if(StringUtils.isNotNull(user.getPhone()))return user.getPhone();
        else return null;
    }

    /**
     * 账户是否未过期,过期无法验证
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否解锁,锁定的用户无法进行身份验证
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
     *
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用,禁用的用户不能身份验证
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
